package com.pan.crawler.factory.conf;

import com.pan.download5.config.ApplicationConfig;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public enum HeaderConfig {

    INSTANCE;

    private Map<String, String> headerMap = new HashMap<>();

    //    {
    //parse json
//
//        InputStream inputStream = ApplicationConfig.class.getClassLoader()
//                .getResourceAsStream("http/header.json");
//        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//        String headerJson = bufferedReader.lines().reduce((x, y) -> x + y).get();
////        System.out.println("json: \n" + headerJson);
//        String lineRegex = "\"(.*?)\"[\n\\s]*:[\n\\s]*?\"(.*?)\"";
//        Pattern linePattern = Pattern.compile(lineRegex);
//        Matcher headerMatcher = linePattern.matcher(headerJson);
//        for (; headerMatcher.find(); ) {
//            String key = headerMatcher.group(1);
//            String value = headerMatcher.group(2);
//            this.headerMap.put(key, value);
//        }
//    }
    {//parse txt

        InputStream inputStream = ApplicationConfig.class.getClassLoader()
                .getResourceAsStream("http/header.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        Pattern linePattern = Pattern.compile("^([^:]*)\\s*:\\s*(.*)$");
        reader.lines().forEach(line -> {
            Matcher matcher = linePattern.matcher(line);
            if (matcher.find()) {
                String key = matcher.group(1);
                String value = matcher.group(2);
                headerMap.put(key, value);
//                System.out.println("key: " + key);
//                System.out.println("value: " + value);
            }
        });


    }


    public Map<String, String> getHeaderMap() {
        return headerMap;
    }

    public List<String> getHeaderList() {
        return headerMap.entrySet().stream().map(kv -> kv.getKey() + "=" + kv.getValue()).collect(Collectors.toList());
    }
}
